package cn.ecommerce.course.module.users.service.security;

import cn.ecommerce.course.module.users.controller.app.users.vo.SecurityUserVO;
import cn.ecommerce.course.module.users.dal.dataobject.users.RoleDO;
import cn.ecommerce.course.module.users.dal.dataobject.users.UsersDO;
import cn.ecommerce.course.module.users.dal.mysql.users.UsersMapper;
import cn.ecommerce.course.module.users.utils.EmailValidationUtils;
import cn.ecommerce.course.module.users.utils.PhoneValidationUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UsersMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.判断账号是什么类型：手机号、邮箱、用户名
        String accountType = getUserType(username);
        //2.根据用户名查询数据库
        //2.1构建查询条件
        QueryWrapper<UsersDO> queryWrapper = new QueryWrapper<>();
        // 根据账号类型查询，账号类型不同，查询的字段不同，
        queryWrapper.eq(accountType, username);
        UsersDO userDO = userMapper.selectOne(queryWrapper);
        //2.2判断用户是否为空
        if(Objects.isNull(userDO)){
            throw new UsernameNotFoundException("用户不存在");
        }
        // 3.返回UserDetails对象
        return new SecurityUserVO(userDO);
    }

    /**
     * 用户登录账号类型
     * @param username 登录账号
     * @return 登录账号类型
     */
    private String getUserType(String username) {
        if (PhoneValidationUtils.isValidInternationalMobile(username)) {
            return "phone";
        } else if (EmailValidationUtils.isValidEmail(username)) {
            return "email";
        } else {
            return "username";
        }
    }

}
